<?php
/* 
 * Functions for simulating a production environment.
 */

require_once('lib.php');

// typically used as a substitute value for the HREF attribute of an A element
const SIMULATED_EXTERNAL_URL = 'javascript:void(0);';

/**
 * Get bytes of random simulated investment image.
 * @return string Image bytes.
 */
function simulate_investment_img() {
    global $_CONFIG;

    // list images in simulation folder
    $dir = new DirectoryIterator($_CONFIG->simulation_investment_img_dir);
    foreach($dir as $fileinfo) {
        if ($fileinfo->isFile()) {
            $images[] = $fileinfo->getPathname();
        }
    }

    // pick a random image
    $file_name = array_rand_value($images);

    // read image bytes to memory
    $fh = fopen($file_name, 'r');
    $image_data = fread($fh, filesize($file_name));
    fclose($fh);

    // TODO scale-down if image too big

    return $image_data;
}

/**
 * Simulate random vote data, used for likes, dislikes, investment proposals.
 * @return string/csv vating data eg 'james,phil,lauren'
 */
function simulate_votes() {
    if (!$count = rand(0, 5)) {
        return;
    }
    for ($i = 0; $i < $count; $i++) {
        $votes[] = simulate_username();
    }
    return ',' . implode(',', $votes);
}

/**
 * Return pseudo username.
 * @return string username
 */
function simulate_username() {
    global $_CONFIG;
    $words = explode(',', file_get_contents('./conf/username.words'));
    $username = array_rand_value($words) . array_rand_value($words) . rand(0, 99);
    if (rand(0, 6) == 0) {
        $username = strtolower($username);
    }
    return substr($username, 0, $_CONFIG->form_max_username_len);
}

/**
 * Return pseudo charity name.
 * @return string charity name
 */
function simulate_charity_name() {
    $words = explode(',', file_get_contents('./conf/charity.words'));
    return array_rand_value($words) . ' ' . array_rand_value($words);
}

/**
 * Produces pseudo Latin text.
 * @param int max length of random text
 * @param int max variance (as a percentage) of length from max length. must
 * be between 0 and 100.
 * @param bool title mode produces a single sentence with no period
 * @return string pseudo text
 */
function simulate_text($max_length, $length_variance, $title_mode=false) {

    // local configuration
    $common_chars = str_split('aefious');
    $uncommon_chars = str_split('bcdghjklmnpqrtvwxyz');
    $SPACE_CHAR = ' '; // useful for debugging
    $MIN_WORDS_PER_SENTENCE = 4;

    // character types
    $CHAR_COMMON = 0;
    $CHAR_UNCOMMON = 1;
    $CHAR_PERIOD = 2;
    $CHAR_SPACE = 3;

    // actual length of text is up to -n% of $approx_length
    $length_modifier = rand(100-$length_variance, 100) / 100;
    $target_length = $max_length * $length_modifier;

    // occurrence of character types is weighted to produce a more natural
    // composition
    $weighted_keys = weighted_key_array(array(
        $CHAR_COMMON => 4,
        $CHAR_UNCOMMON => 3,
        $CHAR_PERIOD => 1,
        $CHAR_SPACE => 2
        ));

    // generate text one character at a time until the target text length is
    // reached. partial sentences at the end of the text are dropped.
    $text = '';
    $sentence = '';
    while (true) {
        switch (array_rand_value($weighted_keys)) {

            case $CHAR_COMMON:
                $sentence .= array_rand_value($common_chars);
                break;

            case $CHAR_UNCOMMON:
                $sentence .= array_rand_value($uncommon_chars);
                break;

            case $CHAR_PERIOD:

                // title mode produces a single sentence without a period
                if ($title_mode) {
                    continue;
                }

                // each sentence must contain a minimum number of words
                $trimmed_sentence = rtrim($sentence, $SPACE_CHAR);
                $space_count = substr_count($trimmed_sentence, $SPACE_CHAR);
                if ($space_count < ($MIN_WORDS_PER_SENTENCE-1)) {
                    continue;
                }

                // first char to uppercase
                $sentence = $trimmed_sentence;
                $sentence[0] = strtoupper($sentence[0]);

                // separate sentences with spaces (the first sentence doesn't
                // need a leading space)
                if (!empty($text)) {
                    $sentence = $SPACE_CHAR . $sentence;
                } 

                // add sentence to text then reset sentence
                $text .= $sentence . '.';
                $sentence = '';
                break;

            case $CHAR_SPACE:

                // space cannot appear at start of sentence or immediately following
                // another space
                if (empty($sentence) || substr($sentence, -1) == $SPACE_CHAR) {
                    continue;
                }

                $sentence .= $SPACE_CHAR;
                break;
        }

        // stop when the required number of chars have been generated
        if (strlen($text) + strlen($sentence) >= $target_length) {

            // in title mode all sentence chars are copied to text once the
            // random number of chars has been reached
            if ($title_mode) {
                $text .= rtrim($sentence, $SPACE_CHAR);
            }
            break;
        }
    }
    return $text;
}

/**
 * Return a random timestamp in the last year
 * @return timestamp result
 */
function simulate_date() {
    return rand(strtotime('-1 year'), time());
}

?>
